<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-20
 * Time: 10:04
 */

namespace doumiaoduo\ueditor;

use yii\helpers\Html;
use yii\widgets\InputWidget;
use yii\helpers\Json;

class ImageUploadMultiple extends InputWidget{

    public $clientOptions = [];

    public $serverParam=[];

    public $showOptions=[];

   public $num = 32;

    public function init(){
        parent::init();
        if(isset($this->clientOptions['serverUrl'])){
            $this->clientOptions['serverUrl']=str_replace('action','',$this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl']=str_replace(urlencode('action'),'',$this->clientOptions['serverUrl']);
        }
        $this->clientOptions['csrf-param']=\Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token']=\Yii::$app->request->getCsrfToken();
        $this->clientOptions['isShow']=false;
    }

    public function run()
    {
        $id=str_replace('-','_',$this->options['id']);
        $strHtml="<div id=\"image-upload-multiple\">";
        $strHtml.="<fieldset>";
        $strHtml.="<legend>图片列表</legend>\n";
        $strHtml.="<div class=\"name-tip\"><i class='iconfont icon-actionwarning'></i>您最多可以同时上传<span> $this->num </span>张</div>\n";
        $strHtml.="<div class=\"pic-list\" id=\"picture_urls_{$id}\">";
        if($this->model->getPrimaryKey()!=null){
            $num = 0;
            if(!empty(Html::getAttributeValue($this->model, 'imageList'))){
                $imageListValues=explode('#|#',Html::getAttributeValue($this->model, 'imageList'));
                $altListValues=explode('#|#',Html::getAttributeValue($this->model, 'altList'));
                $num=count($imageListValues);
            }
//            $imageListValues=Html::getAttributeValue($this->model, 'imageList');
//            $altListValues=Html::getAttributeValue($this->model, 'altList');
            for($i=0;$i<$num;$i++) {
                $is_default = 0;
                if(Html::getAttributeValue($this->model,'picture')==$imageListValues[$i]){
                    $is_default = 1;
                }
                $strHtml .= "<table class='imagefiles' style='float:left;'><tr><td colspan='2'><input class=\"filepath\" name=\"{$id}_urls[]\" value=\"{$imageListValues[$i]}\" style=\"width:50%;\" type=\"hidden\" />";
                $strHtml .= "<input class=\"alt\" name=\"{$id}_alts[]\" value=\"{$altListValues[$i]}\" style=\"width:15%;\"  type=\"hidden\" /></td></tr>";
                $strHtml .= "<tr><td rowspan='2'><img style='width:60px;height:60px;margin-right:5px;margin-right:5px;margin-bottom:5px;' src=\"{$imageListValues[$i]}\"/></td><td>";
                if($is_default==1){
                    $strHtml .= "<label><input type=\"radio\" class=\"defaulturlradio\" name=\"{$id}_isdefault\" value=\"{$imageListValues[$i]}\" checked='checked'/><span style=\"color:black;\">默认图</span></label>&nbsp;&nbsp;";
                }else{
                    $strHtml .= "<label><input type=\"radio\" class=\"defaulturlradio\" name=\"{$id}_isdefault\" value=\"{$imageListValues[$i]}\"/><span style=\"color:black;\">默认图</span></label>&nbsp;&nbsp;";
                }
                $strHtml .= "</td></tr><tr><td><a style=\"cursor: pointer;\" rel=\"remove-img\">移除</a></td></tr>";
                $strHtml .= "</table>";
            }
        }
        $strHtml.="</div></fieldset>";
        $strHtml.=Html::buttonInput('选择图片',['id'=>'image_upload_multiple_button_'.$id,'class'=>'multiple-button yx-choose-img1 yx-radius2']);
        if($this->hasModel()) {
            $strHtml .= Html::activeHiddenInput($this->model, 'imageList');
        }
        if($this->hasModel()) {
            $strHtml .= Html::activeHiddenInput($this->model, 'altList');
        }
        $strHtml .= Html::activeHiddenInput($this->model, 'defaulturl');
        $strHtml.="</div>";
        echo $strHtml;
        $this->registerClientScript();
    }

    public function registerClientScript(){
        $view=$this->getView();
        if(isset($this->showOptions['cssFile'])&&!empty($this->showOptions['cssFile'])){
            UeditorAsset::register($view);
            $view->registerCssFile($this->showOptions['cssFile']);
        }
        else{
            ImageUploadMultipleAsset::register($view);
        }
        $id=str_replace('-','_',$this->options['id']);
        $altListId=Html::getInputId($this->model,'altList');
        $defaulturlId=Html::getInputId($this->model,'defaulturl');
        $options=Json::htmlEncode($this->clientOptions);
        $js="var image_upload_multiple_editor_{$id} = UE.getEditor('image_upload_multiple_button_{$id}',$options); \n";
        $js.="jQuery('#image_upload_multiple_button_{$id}').on('click',function(){image_upload_multiple_editor_{$id}.getDialog('insertimage').open();});\n";
        $js.="image_upload_multiple_editor_{$id}.ready(function() { \n";
        if(!empty($this->serverParam)){
            $params=Json::htmlEncode($this->serverParam);
            $js.="image_upload_multiple_editor_{$id}.execCommand('serverparam', function(editor) { \n";
            $js.="return {$params}; \n";
            $js.="}); \n";
        }

        $js.=<<<JS
        image_upload_multiple_editor_{$id}.addListener('beforeInsertImage', function (t,arg){
            var content=$('#picture_urls_{$id}').html();
            var str='';
            $.each(arg,function(i,item){
                if(content.indexOf(item.src)==-1){
                    var alt=item.title;
                    alt=alt.substring(0,alt.lastIndexOf('.'));
                    str+='<table class="imagefiles" style="float:left"><tr><td colspan="2"><input class="filepath" name="{$id}_urls[]" value="'+item.src+'" style="width:50%;" type="hidden"/>';
                    str+='<input class="alt" name="{$id}_alts[]" value="'+alt+'" style="width:15%;"  type="hidden" /></td></tr>';
                    str+='<tr><td rowspan="2"><img style="width:60px;height:60px;margin-right:5px;margin-bottom:5px;" src="'+item.src+'"/></td><td>';
                    str+='<label><input type="radio" class="defaulturlradio" name="{$id}_isdefault" value="'+item.src+'"/><span style="color:black;">默认图</span></label>&nbsp&nbsp;';
                    str+='</td></tr><tr><td><a style="cursor: pointer;" rel="remove-img">移除</a></td></tr>';
                    str+='</table>';
                }
            });
            $('#picture_urls_{$id}').html(content+str);
            setImageListValue();
        });
        $(document).on('click',"#picture_urls_{$id} a[rel=remove-img]",function(){
            $(this).parents('.imagefiles').remove();
            setImageListValue();
        });
        $(document).on('click','#picture_urls_{$id} .defaulturlradio',function(){
            var defaultimg = $('#picture_urls_{$id} input[name="{$id}_isdefault"]:checked').val();
            $('#{$defaulturlId}').val(defaultimg);
        })
        function setImageListValue(){
            var imageListStr='';
            var artListStr='';
            $('#picture_urls_{$id} .imagefiles').each(function(i,item){
                imageListStr+=(i==0)?$(item).find('input.filepath').val():'#|#'+$(item).find('input.filepath').val();
                artListStr+=(i==0)?$(item).find('input.alt').val():'#|#'+$(item).find('input.alt').val();
            });
            $('#{$this->options['id']}').val(imageListStr);
            $('#{$altListId}').val(artListStr);
        }
JS;
        $js.="}); \n";
        $view->registerJs($js);
    }

}